package com.fl.nettydemo.c5;

import com.fl.nettydemo.handler.ByteUntil;
import com.fl.nettydemo.handler.MyDecoder;
import com.fl.nettydemo.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 测试滑动窗口客户端
 */
@Slf4j
public class HelloWorldServer {

    public static void main(String[] args) {
        start();
    }

    private static void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new MyDecoder());
                            pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                            //定时器
                            pipeline.addLast("IdleStateHandler",new IdleStateHandler(20, 0, 0, TimeUnit.SECONDS));
                            // 自定义处理事件
                            pipeline.addLast("ServerHandler",new ServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(1000).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error...{}", e);
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
